/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package frame;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import sun.jdbc.odbc.JdbcOdbc;

public class Configurate extends javax.swing.JFrame {

   String serverName, databaseName, userName, password;
   
    public Configurate() {
        initComponents();
        
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        Dimension ds = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((ds.width - this.getWidth()) / 2, (ds.height - this.getHeight()) / 2);
        
        
        //enabled button Save and Coonect befor test 
        btnSave.setEnabled(false);
        btnConnect.setEnabled(false);
        
        //check file jdbc.properties valid
        String patch = "C:\\Users\\Thien\\Desktop\\hvaptechkbcquiz\\src\\kbcquiz\\Config.properties";
        File fileName = new File(patch);
        if (fileName.exists()) {
            readFile(patch);
        } else {
            
        }
    }
    
    public Configurate(String serverName, String databaseName, String userName, String password) {
        this.serverName = serverName;
        this.databaseName =databaseName;
        this.userName=userName;
        this.password=password;
        initComponents();
        btnSave.setEnabled(false);
        btnConnect.setEnabled(false);
        String patch = "C:\\Users\\Thien\\Desktop\\hvaptechkbcquiz\\src\\kbcquiz\\Config.properties";
        File fileName = new File(patch);
        if (fileName.exists()) {
            readFile(patch);   
        }
    }
    
    public java.sql.Connection connect_datbase1() {
        java.sql.Connection con = null;
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            con = DriverManager.getConnection("jdbc:sqlserver://" + serverName + ":" + "1433" + ";databaseName=" + databaseName + "", "" + userName + "", "" + password + "");

            if (con != null) {
                btnSave.setEnabled(true);
                btnConnect.setEnabled(true);
                btnTest.setEnabled(false);
                return con;
            }
        } catch (Exception e) {
            //JOptionPane.showMessageDialog(rootPane, "Connect False");
        }

        return con;
    }
    public java.sql.Connection connect_datbase(String serverName, String databaseName, String userName, String password) {
        java.sql.Connection con = null;
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            con = DriverManager.getConnection("jdbc:sqlserver://" + serverName + ":" + "1433" + ";databaseName=" + databaseName + "", "" + userName + "", "" + password + "");

            if (con != null) {
                JOptionPane.showMessageDialog(rootPane, "Connect Success !!!");
                btnSave.setEnabled(true);
                btnConnect.setEnabled(true);
                btnTest.setEnabled(false);
                return con;
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "Connect False");
        }

        return con;
    }
    
    private void readFile(String patch){
        FileInputStream  fileInputStream = null;
        try {
            File fileName = new File(patch);
            fileInputStream = new FileInputStream(fileName);
            DataInputStream  dataInputStream = new DataInputStream(fileInputStream);
            
            
            serverName = dataInputStream.readUTF();
            databaseName = dataInputStream.readUTF();
            userName = dataInputStream.readUTF();
            password = dataInputStream.readUTF();
            
            
            txtServer.setText(serverName);
            txtDatabase.setText(databaseName);
            txtUser.setText(userName);
            txtPassword.setText(password);
           
            
        } catch (IOException ex) {
            Logger.getLogger(Configurate.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException ex) {
                Logger.getLogger(Configurate.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
       
    }
    
    private void createFile(String patch) {
        try {
            File file = new File(patch);
            file.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);

            dataOutputStream.writeUTF(serverName);
            dataOutputStream.writeUTF(databaseName);
            dataOutputStream.writeUTF(userName);
            dataOutputStream.writeUTF(password);

            dataOutputStream.flush();
            dataOutputStream.close();

        } catch (IOException ex) {
        }
    }
 
    private void CheckCreateFile(String patch) {
        File filename = new File(patch);
        if (filename.exists()) {
            filename.delete();
            createFile(patch);
        } else {
            createFile(patch);
        }
    }

    private void runFile(String patch) {
        Configurate v = new Configurate(txtServer.getText(), txtDatabase.getText(), txtUser.getText(), txtPassword.getText());
        v.CheckCreateFile(patch);
    }
    
    private boolean checkValidate(String server,String data,String user,String pass){
        if(server.equals("")){
            JOptionPane.showMessageDialog(rootPane, "Please enter Server Name");
            return false;
        }else if(data.equals("")){
            JOptionPane.showMessageDialog(rootPane, "Please enter Database Name");
            return false;
        }else if(user.equals("")){
            JOptionPane.showMessageDialog(rootPane, "Please enter Username");
            return false;
        }else if(pass.equals("")){
            JOptionPane.showMessageDialog(rootPane, "Please enter Password");
            return false;
        }
        connect_datbase(server, data, user, pass);
        return true;
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtServer = new javax.swing.JTextField();
        txtDatabase = new javax.swing.JTextField();
        txtUser = new javax.swing.JTextField();
        txtPassword = new javax.swing.JPasswordField();
        btnTest = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnConnect = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Configurate");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 0, 0));
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/connect.png"))); // NOI18N
        jLabel1.setText(" Connect System");

        jLabel2.setText("Server Name :");

        jLabel3.setText("Database Name :");

        jLabel4.setText("Username :");

        jLabel5.setText("Password :");

        btnTest.setText("Test");
        btnTest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTestActionPerformed(evt);
            }
        });

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnConnect.setText("Connect");
        btnConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConnectActionPerformed(evt);
            }
        });

        btnExit.setText("Exit");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel2)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel4)
                                .addComponent(jLabel5))
                            .addGap(64, 64, 64)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(0, 0, 0))))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel3)
                            .addGap(36, 36, 36)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(txtDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(46, 46, 46)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnTest, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(55, 55, 55)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnConnect, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnExit, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(26, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnTest)
                    .addComponent(btnConnect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnExit))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTestActionPerformed
        serverName = txtServer.getText();
        databaseName = txtDatabase.getText();
        userName = txtUser.getText();
        password = txtPassword.getText();
        checkValidate(serverName,databaseName,userName, password);
    }//GEN-LAST:event_btnTestActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        String patch = "C:\\Users\\Thien\\Desktop\\hvaptechkbcquiz\\src\\kbcquiz";
        String patch1 = "C:\\Users\\Thien\\Desktop\\hvaptechkbcquiz\\src\\kbcquiz\\Config.properties";
        File fileName = new File(patch);
        if (fileName.exists()) {
            runFile(patch1);
        } else {
            fileName.mkdir();
            runFile(patch1);
        }
        JOptionPane.showMessageDialog(rootPane,"Save Complete");
        btnSave.setEnabled(false);
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed
        Main main = new Main();
        main.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_btnConnectActionPerformed

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
        System.exit(0);
    }//GEN-LAST:event_btnExitActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Configurate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Configurate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Configurate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Configurate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Configurate().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConnect;
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnTest;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField txtDatabase;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtServer;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables
}
